<template>
  <div class="meal-management">
    <!-- 标题 -->
    <!-- <div class="header">
      <h2>欢迎使用培训订餐管理系统</h2>
    </div> -->

    <!-- 餐别筛选 -->
    <div class="meal-filter">
      <span>筛选餐别：</span>
      <el-select
        v-model="lunchType"
        placeholder="午餐"
        class="ml-2"
        style="width: 100px"
      >
        <el-option label="午餐" value="午餐"></el-option>
        <el-option label="晚餐" value="晚餐"></el-option>
      </el-select>

      <el-select
        v-model="orderTrendType"
        placeholder="选择查询类型"
        style="width: 120px; margin-left: 20px"
      >
        <el-option label="按月查询" value="month"></el-option>
        <el-option label="按日查询" value="day"></el-option>
      </el-select>

      <el-date-picker
        v-if="orderTrendType === 'day'"
        v-model="orderTrendDate"
        type="date"
        placeholder="请选择日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        style="width: 150px; margin-left: 10px"
      />

      <el-date-picker
        v-if="orderTrendType === 'month'"
        v-model="orderTrendMonth"
        type="month"
        placeholder="请选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        style="width: 150px; margin-left: 10px"
      />

      <el-select
        v-model="selectedTraining"
        placeholder="请选择培训名称"
        style="margin-left: 10px; width: 150px"
        :disabled="trainingNames.length === 0"
      >
        <el-option
          v-for="name in trainingNames"
          :key="name"
          :label="name"
          :value="name"
        ></el-option>
      </el-select>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" :style="{ background: '#eaf6ff' }">
        <div class="stat-item">
          <span>今日订餐人数</span>
          <div class="stat-value">{{ todayOrderNum }}</div>
        </div>
      </el-card>
      <el-card class="stat-card" :style="{ background: '#f3ffe7' }">
        <div class="stat-item">
          <span>今日核销人数</span>
          <div class="stat-value">{{ WrittenOffNum }}</div>
        </div>
      </el-card>

      <el-card class="stat-card" :style="{ background: '#fff9e6' }">
        <div class="stat-item">
          <span>今日未核销人数</span>
          <div class="stat-value">{{ noWrittenOffNum }}</div>
        </div>
      </el-card>

      <el-card class="stat-card" :style="{ background: '#ffeefa' }">
        <div class="stat-item">
          <span>核销率</span>
          <div class="stat-value">{{ WrittenOffRate }}</div>
        </div>
      </el-card>
    </div>

    <!-- 中间4张图表区域 -->
    <div class="charts-grid">
      <!-- 1. 培训订餐人数总览 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="chart-title">培训订餐人数总览</div>
        </div>
        <div class="chart-container-wrapper">
          <div class="chart-container-scrollable" ref="orderTrendChartWrapper">
            <div class="chart-container" ref="orderTrendChart"></div>
          </div>
        </div>
      </el-card>

      <!-- 2. 订餐情况总览 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="chart-title">订餐情况总览</div>
        </div>
        <div class="chart-container" ref="orderOverviewChart"></div>
      </el-card>

      <!-- 3. 核销情况总览 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="chart-title">核销情况总览</div>
        </div>
        <div class="chart-container" ref="checkTrendChart"></div>
      </el-card>

      <!-- 表格区域 -->
      <el-card class="table-card">
        <div class="table-header">
          <div class="table-header-left">
            <span class="table-title">培训用餐统计</span>
          </div>
        </div>
        <div class="table-wrapper">
          <el-table 
            :data="tableData" 
            border 
            style="width: 100%"
            :row-style="{ height: '50px' }"
            :cell-style="{ padding: '5px 0' }"
          >
            <el-table-column
              prop="trainingName"
              label="培训名称"
            ></el-table-column>
            <el-table-column
              prop="totalOrdered"
              label="订餐总人次"
            ></el-table-column>
            <el-table-column
              prop="verifiedCount"
              label="已核销人次"
            ></el-table-column>
            <el-table-column
              prop="verificationRate"
              label="核销率"
            ></el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup name="Index">
import { ref, onMounted, watch } from "vue";
import { ElInput, ElSelect, ElOption, ElCard, ElButton } from "element-plus";
import * as echarts from "echarts";
import {
  getVerifyCount,
  getOrderCount,
  getTrainingOrder,
  getMealStatistics,
  getDeptsByTrainingName,
  getDetailVerify,
} from "@/api/stastictics/statictics";

const todayOrderNum = ref(245);
const WrittenOffNum = ref(150);
const noWrittenOffNum = ref(95);
const WrittenOffRate = ref("");
const lunchType = ref("午餐");
const trainingNames = ref([]); // 存储培训名称列表
const selectedTraining = ref(""); // 选中的培训名称
const tableData = ref([]); // 表格数据
const orderTrendDate = ref(""); // 培训订餐人数总览的日期选择
const orderTrendType = ref("month"); // 查询类型：month 或 day
// 在现有的 ref 定义中修改或添加
const orderTrendMonth = ref(new Date().toISOString().slice(0, 7)); // 默认为当前年月，格式为 YYYY-MM // 月份选择
// 图表筛选参数
const regionType = ref(""); // 核销情况总览的区县
const deptOptions = ref([]); // 核销情况总览中的区县选项列表

onMounted(() => {
  // 初始化4张图表
  refreshOrderTrendChart(); // 页面加载时获取真实数据
  renderOrderOverview();
  // renderCheckRatio()
  // 获取统计数据
  fetchVerifyCount();
  fetchTableData();
});

// 页面加载和餐别变化时请求
watch(lunchType, () => {
  fetchVerifyCount();
  // 如果已有选中的培训，重新获取该培训的订餐详情
  if (selectedTraining.value) {
    fetchTrainingOrderData();
  }
});

// 获取当前日期 YYYY-MM-DD 格式
const getCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 监听顶部筛选条件变化，控制表格数据展示
watch([orderTrendType, orderTrendDate, orderTrendMonth], () => {
  fetchTableData();
});

// 获取统计数据
async function fetchVerifyCount() {
  try {
    const day = getCurrentDate();
    const res = await getVerifyCount(day);

    // 根据选择的餐别获取对应数据
    let selectedMealData = null;

    // 查找匹配的餐别数据

    const mealData = res.find((item) => item.mealType === lunchType.value);
    selectedMealData = mealData;

    // 如果找到了匹配的餐别数据，更新统计卡片
    if (selectedMealData) {
      // 更新统计卡片数据
      todayOrderNum.value = selectedMealData.orderedCount || 0;
      WrittenOffNum.value = selectedMealData.verifiedCount || 0;
      noWrittenOffNum.value = selectedMealData.unverifiedCount || 0;
      WrittenOffRate.value = selectedMealData.verificationRate || "0%";
    } else {
      // 没有找到匹配的数据，重置为默认值
      todayOrderNum.value = 0;
      WrittenOffNum.value = 0;
      noWrittenOffNum.value = 0;
      WrittenOffRate.value = "0%";
    }
  } catch (e) {
    console.error("获取统计数据失败:", e);
    todayOrderNum.value = 0;
    WrittenOffNum.value = 0;
    noWrittenOffNum.value = 0;
    WrittenOffRate.value = "0%";
  }
}
// 获取培训订餐详情数据
async function fetchTrainingOrderData() {
  try {
    const res = await getTrainingOrder(selectedTraining.value);
    // console.log('培训订餐详情数据:', res)

    if (res && res.data) {
      renderOrderOverview(res.data);
    } else {
      // 如果没有数据，显示空图表
      renderOrderOverview([]);
    }
  } catch (error) {
    console.error("获取培训订餐详情失败:", error);
    renderOrderOverview([]);
  }
}
// 获取所有培训名称
async function fetchAllTrainingNames() {
  try {
    let year = new Date().getFullYear().toString();
    let month = String(new Date().getMonth() + 1).padStart(2, "0"); // 默认当前月份

    // 根据查询类型确定年份和月份
    if (orderTrendType.value === "day" && orderTrendDate.value) {
      const date = new Date(orderTrendDate.value);
      year = date.getFullYear().toString();
      month = String(date.getMonth() + 1).padStart(2, "0");
    } else if (orderTrendType.value === "month" && orderTrendMonth.value) {
      const date = new Date(orderTrendMonth.value);
      year = date.getFullYear().toString();
      month = String(date.getMonth() + 1).padStart(2, "0");
    }
    console.log("查询培训订餐人数总览的参数:", year, month);
    // 调用培训订餐人数总览接口获取所有培训名称
    const res = await getOrderCount(
      year,
      month,
      null, // 日期设为null以获取整月数据
      null // 餐别设为null
    );
    console.log("培训订餐人数总览接口返回数据:", res.data);

    // 初始化培训名称数组
    let allTrainingNames = [];

    // 只有当返回数据存在且为数组时才处理
    if (res && res.data && Array.isArray(res.data) && res.data.length > 0) {
      // 过滤出包含trainingName的项并去重
      allTrainingNames = [
        ...new Set(
          res.data.map((item) => item.trainingName).filter((name) => name)
        ),
      ];
    }

    // 更新培训名称列表
    trainingNames.value = allTrainingNames;

    // 只有当培训名称列表不为空且当前选择为空时才设置默认值
    if (allTrainingNames.length > 0) {
      selectedTraining.value = allTrainingNames[0];
    }

    console.log("默认选中的培训名称:", selectedTraining.value);
    return allTrainingNames;
  } catch (error) {
    console.error("获取培训名称失败:", error);
    trainingNames.value = [];
    // 重置选择的培训名称
    selectedTraining.value = "";
    return [];
  }
}

// 修改 fetchTableData 函数，移除月份为空的判断，直接使用当前值
async function fetchTableData() {
  try {
    let monthToQuery = "";

    // 根据查询类型确定月份参数
    if (orderTrendType.value === "day" && orderTrendDate.value) {
      // 按日查询时，提取日期中的月份
      const date = new Date(orderTrendDate.value);
      monthToQuery = `${date.getFullYear()}-${String(
        date.getMonth() + 1
      ).padStart(2, "0")}`;
    } else if (orderTrendType.value === "month" && orderTrendMonth.value) {
      // 按月查询时，直接使用选择的月份
      monthToQuery = orderTrendMonth.value;
    } else {
      // 默认使用当前月份
      monthToQuery = new Date().toISOString().slice(0, 7);
    }

    // 调用接口获取数据
    const res = await getMealStatistics(monthToQuery);
    tableData.value = res;
  } catch (error) {
    console.error("获取表格统计数据失败:", error);
    tableData.value = [];
  }
}

// 监听选中培训名称变化
watch(selectedTraining, () => {
  // 重新获取培训订餐详情数据,第二幅图订餐情况总览
  fetchTrainingOrderData();
});

// 监听培训订餐人数总览的筛选条件变化
watch([orderTrendType, orderTrendDate, orderTrendMonth, lunchType], () => {
  refreshOrderTrendChart();
});

// 监听核销情况总览的筛选条件变化
watch([lunchType, regionType, selectedTraining], () => {
  console.log(
    "核销情况总览的筛选条件变化:",
    lunchType.value,
    regionType.value,
    selectedTraining.value
  );
  refreshCheckTrendChart();
});

// ECharts 实例
const orderTrendChart = ref(null);
const orderOverviewChart = ref(null);
const checkTrendChart = ref(null);
// const checkRatioChart = ref(null)

// 刷新培训订餐人数图表
// 修改 refreshOrderTrendChart 函数
async function refreshOrderTrendChart() {
  try {
    let yearValue,
      monthValue,
      dayValue = null;

    if (orderTrendType.value === "day" && orderTrendDate.value) {
      // 按日查询
      const date = new Date(orderTrendDate.value);
      yearValue = date.getFullYear().toString();
      monthValue = String(date.getMonth() + 1).padStart(2, "0");
      dayValue = String(date.getDate()).padStart(2, "0");
    } else if (orderTrendType.value === "month" && orderTrendMonth.value) {
      // 按月查询
      const date = new Date(orderTrendMonth.value);
      yearValue = date.getFullYear().toString();
      monthValue = String(date.getMonth() + 1).padStart(2, "0");
      dayValue = null; // 关键：按月查询时不传递日期参数
    } else {
      // 默认使用当前月份进行查询
      const now = new Date();
      yearValue = now.getFullYear().toString();
      monthValue = String(now.getMonth() + 1).padStart(2, "0");
      // 默认按月查询，不传递具体日期
      if (orderTrendType.value === "month") {
        dayValue = null;
      } else {
        dayValue = String(now.getDate()).padStart(2, "0");
      }
    }

    const res = await getOrderCount(
      yearValue,
      monthValue,
      dayValue, // 当为null时，后端应返回整月数据
      lunchType.value
    );
    console.log(
      "查询的参数:",
      yearValue,
      monthValue,
      dayValue,
      lunchType.value
    );
    console.log("查询结果:", res);

    // 获取所有培训名称
    await fetchAllTrainingNames();
    // 在获取培训名称后，再刷新核销情况总览图表
    await refreshCheckTrendChart();

    if (res && res.data && Array.isArray(res.data)) {
      renderOrderTrendWithData(res.data);
    } else {
      // 如果没有数据，显示空图表
      renderEmptyOrderTrend();
    }
  } catch (error) {
    console.error("获取订餐统计数据失败:", error);
    // 出错时显示空图表
    renderEmptyOrderTrend();
  }
}
// 刷新核销情况总览图表
async function refreshCheckTrendChart() {
  if (!selectedTraining.value) return;
  try {
    // 确保 trainingNames 不为空
    if (!trainingNames.value || trainingNames.value.length === 0) {
      console.log("培训名称列表为空，等待获取培训名称...");
      // 如果培训名称列表为空，先获取培训名称
      await fetchAllTrainingNames();
    }

    // 确定要使用的培训名称
    let trainingName = "";

    // 优先使用用户选择的培训名称
    if (selectedTraining.value) {
      trainingName = selectedTraining.value;
    }
    // 如果没有选择，但已有培训名称列表，使用第一个
    else if (trainingNames.value && trainingNames.value.length > 0) {
      trainingName = trainingNames.value[0];
      // 同时设置 selectedTraining的值
      selectedTraining.value = trainingName;
    }

    // 如果仍然没有培训名称，渲染空图表
    if (!trainingName) {
      renderCheckTrendWithData(null);
      return;
    }

    const res = await getDetailVerify(
      trainingName,
      regionType.value,
      lunchType.value
    );
    renderCheckTrendWithData(res);
  } catch (error) {
    console.error("获取核销详情失败:", error);
    renderCheckTrendWithData(null);
  }
}

// 1. 培训订餐人数总览（柱状图）- 带数据
function renderOrderTrendWithData(data) {
  // 处理数据
  if (!data || data.length === 0) {
    // 没有数据时显示默认空图表
    const instance = echarts.init(orderTrendChart.value);
    instance.setOption({
      xAxis: { type: "category", data: [] },
      yAxis: { type: "value" },
      series: [
        { name: "总人数", type: "bar", data: [] },
        { name: "除市公司人数", type: "bar", data: [] },
      ],
      legend: { data: ["总人数", "除市公司人数"] },
    });
    return;
  }

  // 处理数据
  const trainingNames = [];
  const totalOrders = [];
  const districtOrders = [];

  data.forEach((item) => {
    trainingNames.push(item.trainingName);
    totalOrders.push(item.orderTotal);
    districtOrders.push(item.districtOrderTotal);
  });

  // 计算图表所需的最小宽度
  const minBarWidth = 80; // 每个柱状图组的最小宽度
  const barGap = 20; // 柱状图组之间的间距
  const minChartWidth = trainingNames.length * (minBarWidth + barGap) + 120; // 加上左右边距
  const containerWidth = 600; // 容器默认宽度

  // 如果需要的宽度超过容器宽度，则设置图表容器的宽度并启用滚动
  if (minChartWidth > containerWidth) {
    orderTrendChart.value.style.width = minChartWidth + "px";
  } else {
    orderTrendChart.value.style.width = "100%";
  }

  // 初始化或重新初始化图表
  if (window.orderTrendChartInstance) {
    window.orderTrendChartInstance.dispose();
  }
  window.orderTrendChartInstance = echarts.init(orderTrendChart.value);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
    left: 0,  // 从 50 减少到 30，向左移动
    right: 100,
    bottom: trainingNames.some((name) => name.length > 6) ? 55 : 30,
    top: 45,
    containLabel: true,
  },
    legend: {
      data: ["总人数", "除市公司人数"],
      top: 10,
      left: "center",
      orient: "horizontal",
      itemGap: 20,
    },
    grid: {
      left: '4%',
      right: '5%',
      bottom: 50,
      top: 45,
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: trainingNames,
      axisTick: {
        alignWithLabel: true,
        interval: 0,
      },
      axisLabel: {
        fontSize: 14,
        interval: 0, // 显示所有标签
        // rotate: trainingNames.length > 8 ? 45 : 0, // 数据过多时旋转标签
        margin: 5,
        formatter: function (value) {
          // 如果标签太长，进行截断处理
          if (value.length > 6) {
            return value.substring(0, 6) + "...";
          }
          return value;
        },
      },

    },
    yAxis: {
      type: "value",
      name: "订餐人数",
      nameLocation: "end",
      nameGap: 20,
      nameTextStyle: {
        fontSize: 14,
      },
      axisLabel: {
        fontSize: 12,
      },
    },
    series: [
      {
        name: "总人数",
        type: "bar",
        barWidth: "40",
        data: totalOrders,
        label: {
          show: true,
          position: "top",
          fontSize: 10,
        },
        itemStyle: { color: "#98CFE6" },
      },
      {
        name: "除市公司人数",
        type: "bar",
        barWidth: "40",
        data: districtOrders,
        label: {
          show: true,
          position: "top",
          fontSize: 10,
        },
        itemStyle: { color: "#ADE7A8" },
      },
    ],
  };

  window.orderTrendChartInstance.setOption(option);

  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener("resize", () => {
    if (window.orderTrendChartInstance) {
      window.orderTrendChartInstance.resize();
    }
  });
}


// 2. 订餐情况总览（分组柱状图）
function renderOrderOverview(data) {
  const instance = echarts.init(orderOverviewChart.value);

  // 处理数据
  if (!data || data.length === 0) {
    // 没有数据时显示默认空图表
    instance.setOption({
      xAxis: { type: "category", data: [] },
      yAxis: { type: "value" },
      series: [
        { name: "午餐", type: "bar", data: [], stack: "total" },
        { name: "晚餐", type: "bar", data: [], stack: "total" },
      ],
      legend: { data: ["午餐", "晚餐"] },
    });
    return;
  }

  // 按日期分组数据
  const dateMap = new Map();

  data.forEach((item) => {
    // 提取月日作为键，例如: 0820
    const date = new Date(item.mealDate);
    const monthDay = `${String(date.getMonth() + 1).padStart(2, "0")}${String(
      date.getDate()
    ).padStart(2, "0")}`;

    if (!dateMap.has(monthDay)) {
      dateMap.set(monthDay, { lunch: 0, dinner: 0 });
    }

    const dayData = dateMap.get(monthDay);
    if (item.mealType === "午餐") {
      dayData.lunch = item.countTrOr;
    } else if (item.mealType === "晚餐") {
      dayData.dinner = item.countTrOr;
    }
  });

  // 构造x轴数据和系列数据
  const dates = Array.from(dateMap.keys()).sort();
  const lunchData = dates.map((date) => dateMap.get(date).lunch);
  const dinnerData = dates.map((date) => dateMap.get(date).dinner);

  instance.setOption({
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: '4%',
      right: '5%',
      bottom: 50,
      top: 45,
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: dates,
      //横坐标文字变大
      axisLabel: {
        fontSize: 14, // 文字大小（默认12，数值越大越大）
        rotate: 0, // 可选：旋转30度防止文字重叠（根据需要调整）
      },
    },
    yAxis: {
      type: "value",
      name: "人次", // 标识文本
      nameLocation: "end", // 标识位置（middle/start/end）
      nameGap: 30, // 标识与坐标轴的距离
      nameTextStyle: {
        fontSize: 14, // 标识文字大小
        // fontWeight: 'bold' // 标识文字加粗
      },
    },
    series: [
      {
        name: "午餐",
        type: "bar",
        barWidth: "40",
        data: lunchData,
        stack: "total",
        itemStyle: { color: "#98CFE6" },
        label: {
          show: true,
          position: "inside",
          formatter: (params) => {
            return params.value === 0 ? "" : params.value;
          },
          fontSize: 12,
          color: "#333", // 设置标签文字颜色，确保在不同背景色下都可见
        },
      },
      {
        name: "晚餐",
        type: "bar",
        barWidth: "40",
        data: dinnerData,
        stack: "total",
        itemStyle: { color: "#ADE7A8" },
        label: {
          show: true,
          position: "inside",
          formatter: (params) => {
            return params.value === 0 ? "" : params.value;
          },
          fontSize: 12,
          color: "#333", // 设置标签文字颜色，确保在不同背景色下都可见
        },
      },
    ],
    legend: {
      data: ["午餐", "晚餐"],
    },
  });
}

// 3. 核销情况总览（柱状图）- 带数据
function renderCheckTrendWithData(data) {
  const instance = echarts.init(checkTrendChart.value);

  // 处理数据
  if (!data || !data.details || !Array.isArray(data.details)) {
    // 没有数据时显示空图表
    instance.setOption({
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
      },
    });
    return;
  }

  // 按日期聚合数据
  const dateMap = new Map();
  data.details.forEach((item) => {
    const date = item.dayMmdd;
    if (!dateMap.has(date)) {
      dateMap.set(date, {
        verifiedCnt: 0,
        unverifiedCnt: 0,
      });
    }

    const dateData = dateMap.get(date);
    dateData.verifiedCnt += item.verifiedCnt || 0;
    dateData.unverifiedCnt += item.unverifiedCnt || 0;
  });

  // 构造x轴数据和系列数据
  const dates = Array.from(dateMap.keys()).sort();
  const verifiedData = dates.map((date) => dateMap.get(date).verifiedCnt);
  const unverifiedData = dates.map((date) => dateMap.get(date).unverifiedCnt);

  // 计算y轴最大值，增加一些顶部空间以便更好地显示标签
  const allValues = [...verifiedData, ...unverifiedData];
  const maxValue = Math.max(...allValues);
  const yAxisMax = maxValue > 0 ? Math.ceil(maxValue * 1.2) : 10; // 增加20%的空间

  instance.setOption({
    tooltip: {
      trigger: "axis",
    },
        grid: {
      left: '4%',
      right: '5%',
      bottom: 50,
      top: 45,
      containLabel: true,
    },
    legend: {
      data: ["已核销", "未核销"],
    },
    xAxis: {
      type: "category",
      data: dates,
      //横坐标文字变大
      axisLabel: {
        fontSize: 14, // 文字大小（默认12，数值越大越大）
        rotate: 0, // 可选：旋转30度防止文字重叠（根据需要调整）
      },
    },
    yAxis: {
      type: "value",
      max: yAxisMax, // 设置y轴最大值
      name: "核销人次", // 标识文本
      nameLocation: "end", // 标识位置（middle/start/end）
      nameGap: 30, // 标识与坐标轴的距离
      nameTextStyle: {
        fontSize: 14, // 标识文字大小
        // fontWeight: 'bold' // 标识文字加粗
      },
    },

    series: [
      {
        name: "已核销",
        type: "bar",
        barWidth: "40",
        data: verifiedData,
        itemStyle: { color: "#92B6EC" },
        label: {
          show: true,
          position: "top",
          formatter: (params) => {
            return params.value === 0 ? "" : params.value;
          },
        },
      },
      {
        name: "未核销",
        type: "bar",
        barWidth: "40",
        data: unverifiedData,
        itemStyle: { color: "#E6ABAB" },
        label: {
          show: true,
          position: "top",
          formatter: (params) => {
            return params.value === 0 ? "" : params.value;
          },
        },
      },
    ],
  });
}
</script>

<style scoped>
/* 添加对齐控制样式 */
.aligned-control {
  vertical-align: top;
}

.chart-controls-left .el-select .el-input,
.chart-controls-left .el-date-editor .el-input,
.date-select-group .el-select .el-input,
.date-select-group .el-date-editor .el-input {
  vertical-align: top;
}

/* 确保所有控件的输入框高度一致 */
.chart-controls-left .el-select .el-input__inner,
.date-select-group .el-select .el-input__inner {
  height: 32px; /* 与日期选择器高度保持一致 */
  line-height: 32px;
}
.meal-management {
  padding: 20px;
  background: #f8f9fa;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.chart-container {
  margin-top: 20px;
  min-width: 600px;
  /* 根据数据量和固定柱状图宽度计算总宽度 */
  width: v-bind("`${Math.max(trainingNames.length * 120, 600)}px`");
  height: 280px;
  border: 1px solid #eff1f5;
  background: white;
}

@media (max-width: 768px) {
  .chart-container {
    width: v-bind("`${Math.max(trainingNames.length * 80, 400)}px`");
  }
}

/* 表格卡片样式优化 */

.table-card {
  padding: 20px;
  height: 400px; /* 固定卡片高度 */
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.table-card ::v-deep(.el-table) {
  flex: 1;
  overflow-y: auto;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-wrapper ::v-deep(.el-table) {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-wrapper ::v-deep(.el-table__header-wrapper) {
  flex-shrink: 0;
}

.table-wrapper ::v-deep(.el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto !important;
  height: 100%;
}

/* 表格包装器样式 */
.table-wrapper {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-wrapper ::v-deep(.el-table) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-wrapper ::v-deep(.el-table__header-wrapper) {
  flex-shrink: 0;
}

.table-wrapper ::v-deep(.el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto;
}

/* 新增的餐别筛选样式 */
.meal-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
}

.meal-filter span {
  margin-right: 10px;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-item {
  font-size: 20px;
  height: 10px;
  display: center;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 50px;
  color: #343a40;
}

.stat-item .stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #495057;
  margin-top: 5px;
  text-align: center;
  display: flex;
  justify-content: center;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  flex-shrink: 0;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart-controls-wrapper {
  width: 100%;
}

.chart-controls-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.date-select-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.chart-controls-right {
  display: flex;
  align-items: center;
  white-space: nowrap;
}
/* 所有图表容器居中显示 */
.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 280px;
  border: 1px solid #eff1f5;
  background: white;
  margin: 0;
}

/* 培训订餐人数总览图表容器样式 */
.chart-container-wrapper {
  width: 100%;
  height: 300px;
  display: flex;
}

.chart-container-scrollable {
  width: 100%;
  height: 300px;
  overflow-x: auto;
  overflow-y: hidden;
  position: relative;
}

/* 滚动条样式优化 */
.chart-container-scrollable::-webkit-scrollbar {
  height: 8px;
}

.chart-container-scrollable::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.chart-container-scrollable::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.chart-container-scrollable::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.table-card {
  padding: 20px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.table-header-left {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  white-space: nowrap;
}

.table-date-picker {
  width: 200px;
  border-radius: 4px;
}


/* 订餐情况总览 */
.chart-controls-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
}

.chart-controls-left .el-select,
.chart-controls-left .el-date-editor {
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .table-header-left {
    width: 100%;
  }

  .table-date-picker {
    flex: 1;
    min-width: 150px;
  }

  .chart-controls-flex {
    flex-direction: column;
    align-items: stretch;
  }

  .chart-controls-left {
    flex-wrap: wrap;
    margin-bottom: 10px;
  }

  .chart-controls-right {
    align-self: flex-end;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-cards {
    flex-direction: column;
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }

  .chart-controls {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
